<template>
  <div class="upload-container">
    <div :style="containerStyle">
      <el-upload
        ref="elUpload"
        :action="upload_qiniu_url"
        :data="dataObj"
        :multiple="false"
        :show-file-list="false"
        :on-success="handleImageSuccess"
        :on-error="handleError"
        :on-progress="uploadImageProcess"
        :on-change="handleFileChange"
        :before-upload="beforeUpload"
        :disabled="isDisabled"
        class="image-uploader"
        drag
      >
        <img v-if="imageUrl" :src="imageUrl" :style="imageStyle" class="image-preview">
        <el-progress
          v-else-if="progressFlag"
          :percentage="uploadPercent"
          :width="progressWidth"
          :show-text="progressTextShow"
          :style="progressStyle"
          type="circle"/>
        <div v-else>
          <i :style="iconStyle" class="el-icon-plus"/>
        </div>
      </el-upload>
    </div>
    <div v-if="tipString" class="el-upload__tip">{{ tipString }}</div>
  </div>
</template>

<script>
import { getToken } from '@/api/medium';

/**
 * 〖Author〗 MiWi.LIN ＾＾＾＾〖E-mail〗 80383585@qq.com
 * ======================================================== Copyright(c) 2018/9/14 ==
 * 〖Version〗 1.0 <BR/>
 * 〖Date〗 2018/9/14_下午1:46 <BR/>
 * 〖Desc〗 单图上传组件，含图片预览、上传进度 <BR/>
 * 〖Modify By〗 <BR/>
 */
const {
  UPLOAD_QINIU_URL,
  BUCKET_QINIU_HOST
} = process.env;

export default {
  name: 'SingleImageUpload',
  props: {
    mediumImgIndex: {
      type: Number,
      default: 0
    },
    value: { // v-model绑定
      type: String,
      default: ''
    },
    iconSize: { // 上传图标大小
      type: Number,
      default: 12
    },
    width: { // 组件宽
      type: Number,
      default: 100
    },
    height: { // 组件高
      type: Number,
      default: 100
    },
    tipString: { // 提示
      type: String,
      default: ''
    },
    isDisabled: { // 是否禁止上传
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      upload_qiniu_url: UPLOAD_QINIU_URL,
      bucketHost: '', // 图片上传后的Host
      progressFlag: false,
      uploadPercent: 0,
      dataObj: { // 上传参数
        token: '',
        key: ''
      }
    };
  },
  computed: {
    imageUrl() {
      return this.value;
    },
    containerStyle() { // 设置组件和图片宽高
      return {
        'width': `${this.width}px`,
        'height': `${this.height}px`
      };
    },
    imageStyle() {
      return {
        'width': `${this.width - 2}px`, // 扣Border
        'height': `${this.height}px`
      };
    },
    iconStyle() { // 计算图标居中
      return {
        'font-size': `${this.iconSize}px`,
        'padding-top': `${(this.height - this.iconSize) / 2}px`,
        'padding-bottom': `${(this.height - this.iconSize) / 2}px`,
        'line-height': `${this.iconSize}px`,
        'color': '#6e8fa2'
      };
    },
    progressStyle() {
      const margin = (this.height - this.progressWidth) / 2;
      return {
        'margin-top': `${margin}px`,
        'margin-bottom': `${margin}px`
      };
    },
    progressMax() { // 获得最短边
      return this.width > this.height ? this.height : this.width;
    },
    progressWidth() {
      const width = this.progressMax * 0.8;
      return width > 100 ? 100 : width; // 进度条直径最大100
    },
    progressTextShow() { // 进度条文字在直径小于35时隐藏
      return this.progressWidth >= 35;
    }
  },
  methods: {
    rmImage() {
      this.emitInput('');
    },
    emitInput(val) {
      this.$emit('input', val);
    },
    uploadImageProcess(event, file) {
      this.progressFlag = true;
      this.uploadPercent = Number(file.percentage.toFixed(0));
    },
    handleFileChange() { // params: file, fileList
      // this.$refs.elUpload.submit();
    },
    handleImageSuccess(respone, file) { // params: respone, file, fileList
      this.progressFlag = false;
      // this.emitInput(respone.files.file);
      this.emitInput(`${this.bucketHost}/${encodeURI(respone.key)}`);
      // this.tempImageUrl = URL.createObjectURL(file.raw);
      this.$emit('uploadImgSuccess', {
        img: `${this.bucketHost}/${encodeURI(respone.key)}`,
        index: this.mediumImgIndex
      });
    },
    handleError(respone) {
      console.info(respone);
      this.rmImage();
      this.progressFlag = false;
      this.$message({
        message: '上传失败',
        duration: 2000,
        type: 'warning'
      });
    },
    beforeUpload(file) {
      if (!this.checkFile(file)) {
        return false;
      }
      // return true; // TEST
      // 设置文件名、获得上传TOKON
      const curr = moment().format('YYYYMMDD').toString();
      const prefix = file.lastModified.toString();
      const name = encodeURI(file.name);
      const length = name.length - 20;
      const filename = length > 0 ? name.slice(length) : name;
      this.dataObj.key = `${curr}/${prefix}_${file.size}_${filename}`;
      const _self = this;
      return new Promise((resolve, reject) => {
        getToken().then(response => {
          // const key = response.data.key;
          const token = response.data.token;
          const bucketHost = response.data.bucketHost;
          this.bucketHost = bucketHost || BUCKET_QINIU_HOST;
          _self._data.dataObj.token = token;
          // _self._data.dataObj.key = key;
          resolve(true);
        }, result => {
          this.$message({
            type: 'error',
            message: result.message
          });
        }).catch(err => {
          console.log(err);
          reject(false);
        });
      });
    },
    checkFile(file) { // 判断文件格式大小
      // const isJPG = file.type === 'image/jpeg';
      // const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG && !isPNG) {
      //   this.$message.error('图片只能是 JPG/PNG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
      }
      // return (isJPG || isPNG) && isLt2M;
      return isLt2M;
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
  $bg: #2d3a4b;
  $light_gray: #eee;

  /* reset element-ui css */
  .upload-container {
    width: auto !important;
    .el-upload {
      .el-upload-dragger {
        height: 100%;
        .el-icon-upload {
          font-size: 30px;
          margin: 0px;
          line-height: 30px;
        }
      }
    }
  }

</style>
<style rel="stylesheet/scss" lang="scss" scoped>

  .upload-container {
    width: 100%;
    line-height: 0px;
    position: relative;
    @include clearfix;

    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #406EFF;
    }
    .image-uploader {
      width: 100%;
      float: left;
    }
    .el-upload__tip {
      margin-top: 5px;
      line-height: 14px;
      color: #B1B1B1;
    }
  }
</style>
